<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>K-line Functionality Test</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ccc; border-radius: 5px; }
        .success { color: green; }
        .error { color: red; }
        .warning { color: orange; }
        .test-result { margin: 10px 0; padding: 10px; background: #f5f5f5; border-radius: 3px; }
        button { margin: 5px; padding: 8px 15px; cursor: pointer; }
        #websocket-log { height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; font-family: monospace; font-size: 12px; }
    </style>
</head>
<body>
    <h1>Dynamic K-line Data Functionality Test</h1>
    
    <div class="test-section">
        <h2>WebSocket Connection Test</h2>
        <button onclick="testWebSocketConnection()">Test WebSocket Connection</button>
        <button onclick="simulateKlineData()">Simulate K-line Data</button>
        <button onclick="clearLog()">Clear Log</button>
        <div id="websocket-status" class="test-result">Status: Not tested</div>
        <div id="websocket-log"></div>
    </div>
    
    <div class="test-section">
        <h2>Performance Test</h2>
        <button onclick="testBatchRendering()">Test Batch Rendering</button>
        <button onclick="testThrottleMechanism()">Test Throttle Mechanism</button>
        <div id="performance-result" class="test-result">Performance: Not tested</div>
    </div>
    
    <div class="test-section">
        <h2>Error Handling Test</h2>
        <button onclick="testErrorHandling()">Test Error Handling</button>
        <div id="error-result" class="test-result">Error handling: Not tested</div>
    </div>
    
    <div class="test-section">
        <h2>Data Format Test</h2>
        <button onclick="testDataFormat()">Test Data Format Conversion</button>
        <div id="format-result" class="test-result">Data format: Not tested</div>
    </div>

    <script>
        // Test WebSocket connection
        function testWebSocketConnection() {
            const statusEl = document.getElementById('websocket-status');
            const logEl = document.getElementById('websocket-log');
            
            try {
                const ws = new WebSocket('wss://blue.trading-code.com/infra/ws');
                
                ws.onopen = function() {
                    statusEl.innerHTML = '<span class="success">✓ WebSocket Connected Successfully</span>';
                    log('WebSocket connected successfully');
                    
                    // Test subscription
                    ws.send(JSON.stringify({
                        type: 'subscribe',
                        productId: 'test-product-1'
                    }));
                    
                    setTimeout(() => {
                        ws.close();
                    }, 2000);
                };
                
                ws.onmessage = function(event) {
                    log('Received message: ' + event.data);
                };
                
                ws.onerror = function(error) {
                    statusEl.innerHTML = '<span class="error">✗ WebSocket Connection Failed</span>';
                    log('WebSocket error: ' + error);
                };
                
                ws.onclose = function() {
                    log('WebSocket connection closed');
                };
                
            } catch (error) {
                statusEl.innerHTML = '<span class="error">✗ WebSocket Test Error: ' + error.message + '</span>';
                log('WebSocket test error: ' + error.message);
            }
        }
        
        // Simulate K-line data
        function simulateKlineData() {
            const logEl = document.getElementById('websocket-log');
            
            // Simulate the data format from WebSocket
            const mockData = {
                type: 'stock-kline-min1',
                data: {
                    productId: 'test-product-1',
                    timestamp: Date.now(),
                    open: 3975.4,
                    high: 3978.2,
                    low: 3972.1,
                    close: 3976.8,
                    volume: 1250.5,
                    change: 1.4,
                    changePercent: 0.035
                }
            };
            
            log('Simulating K-line data: ' + JSON.stringify(mockData, null, 2));
            
            // Test data format conversion
            const convertedData = {
                time: mockData.data.timestamp,
                value: mockData.data.close
            };
            
            log('Converted data format: ' + JSON.stringify(convertedData));
            log('<span class="success">✓ K-line data simulation completed</span>');
        }
        
        // Test batch rendering performance
        function testBatchRendering() {
            const resultEl = document.getElementById('performance-result');
            const startTime = performance.now();
            
            // Simulate batch processing
            const batchSize = 5;
            const totalItems = 50;
            let processed = 0;
            
            function processBatch() {
                const batchStart = performance.now();
                
                for (let i = 0; i < batchSize && processed < totalItems; i++) {
                    // Simulate processing
                    processed++;
                }
                
                const batchEnd = performance.now();
                
                if (processed < totalItems) {
                    setTimeout(processBatch, 100); // RENDER_INTERVAL = 100ms
                } else {
                    const totalTime = performance.now() - startTime;
                    resultEl.innerHTML = '<span class="success">✓ Batch rendering completed in ' + totalTime.toFixed(2) + 'ms</span>';
                }
            }
            
            processBatch();
        }
        
        // Test throttle mechanism
        function testThrottleMechanism() {
            const resultEl = document.getElementById('performance-result');
            let callCount = 0;
            let executedCount = 0;
            
            // Simulate throttled function (THROTTLE_DELAY = 200ms)
            function throttledFunction() {
                callCount++;
                return ++executedCount;
            }
            
            // Test rapid calls
            const interval = setInterval(() => {
                throttledFunction();
            }, 50); // Call every 50ms
            
            setTimeout(() => {
                clearInterval(interval);
                const efficiency = ((callCount - executedCount) / callCount * 100).toFixed(1);
                resultEl.innerHTML = '<span class="success">✓ Throttle test: ' + callCount + ' calls, ' + executedCount + ' executed, ' + efficiency + '% filtered</span>';
            }, 1000);
        }
        
        // Test error handling
        function testErrorHandling() {
            const resultEl = document.getElementById('error-result');
            
            try {
                // Simulate different error scenarios
                
                // 1. WebSocket connection error
                log('Testing WebSocket connection error handling...');
                
                // 2. Data format error
                const invalidData = "invalid json";
                try {
                    JSON.parse(invalidData);
                } catch (e) {
                    log('✓ Data format error caught: ' + e.message);
                }
                
                // 3. Network timeout simulation
                setTimeout(() => {
                    log('✓ Network timeout handling tested');
                    resultEl.innerHTML = '<span class="success">✓ Error handling mechanisms working</span>';
                }, 1000);
                
            } catch (error) {
                resultEl.innerHTML = '<span class="error">✗ Error handling test failed: ' + error.message + '</span>';
            }
        }
        
        // Test data format conversion
        function testDataFormat() {
            const resultEl = document.getElementById('format-result');
            
            // Test timestamp conversion (seconds to milliseconds)
            const timestampSeconds = 1761281760;
            const timestampMilliseconds = timestampSeconds * 1000;
            
            // Test data structure
            const testData = {
                time: timestampMilliseconds,
                value: 3975.4
            };
            
            // Verify format matches expected structure
            const isValidFormat = typeof testData.time === 'number' && 
                                typeof testData.value === 'number' &&
                                testData.time > 1000000000000; // Should be milliseconds
            
            resultEl.innerHTML = isValidFormat ? 
                '<span class="success">✓ Data format correct: time=' + testData.time + ', value=' + testData.value + '</span>' :
                '<span class="error">✗ Data format incorrect</span>';
        }
        
        // Utility functions
        function log(message) {
            const logEl = document.getElementById('websocket-log');
            const timestamp = new Date().toLocaleTimeString();
            logEl.innerHTML += '[' + timestamp + '] ' + message + '<br>';
            logEl.scrollTop = logEl.scrollHeight;
        }
        
        function clearLog() {
            document.getElementById('websocket-log').innerHTML = '';
        }
        
        // Auto-run basic tests
        window.onload = function() {
            setTimeout(() => {
                testDataFormat();
                simulateKlineData();
            }, 1000);
        };
    </script>
</body>
</html>